package com.dotstone.chipism.util;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

/*************************************************************************
 * 公 司： 深圳市高金科技有限公司 作 者： 深圳市高金科技有限公司 文件名称：WifiAdmin.java 内容摘要： 日 期： 2016-11-28
 ************************************************************************/
public class WifiAdmin {
	private final Context mContext;
	private WifiManager mWifiManager;
	private boolean flag;
	private WifiInfo mWifiInfo;
	private List<ScanResult> mWifiList;
	private List<ScanResult> mAPList;
	private static final int SECURITY_NONE = 1;
	private static final int SECURITY_WEP = 2;
	private static final int SECURITY_PSK = 3;
	private static final int SECURITY_EAP = 4;
	// 网络连接列表
	private List<WifiConfiguration> mWifiConfiguration;

	public WifiAdmin(Context context) {
		mContext = context;
		// mWifiInfo = getConnectionInfo();
		mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		// 取得WifiInfo对象
		mWifiInfo = mWifiManager.getConnectionInfo();
	}

	public void openWifi() {
		if (!mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(true);
		}
	}

	public String getWifiConnectedSsid() {
		// 定义WifiInfo这个类的实例mWifiInfo，将其定义为正在连接中的wifi
		WifiInfo mWifiInfo = getConnectionInfo();
		// 定义ssid字符串
		String ssid = null;
		// 如果mWifiInfo不为空（即有正在连接的wifi），并且wifi处在正在连接的状态

		if (mWifiInfo.getSSID() != null) {
			ssid = mWifiInfo.getSSID();
			// Log.i("Tag", "从wifi管理类拿到ssid = " + mWifiInfo.getSSID());
		}
		if (mWifiInfo != null && isWifiConnected()) {
			// 定义该mWifiInfo的SSID长度len
			int len = mWifiInfo.getSSID().length();
			// 通过判断长度去截取真正的ssid
			// Log.i("Tag", "从wifi管理类拿到ssid = " + mWifiInfo.getSSID());
			if (mWifiInfo.getSSID().startsWith("\"") && mWifiInfo.getSSID().endsWith("\"")) {
				ssid = mWifiInfo.getSSID().substring(1, len - 1);
			} else {
				ssid = mWifiInfo.getSSID();
			}
		}

		return ssid;
	}

	public String getWifiConnectedBssid() {
		WifiInfo mWifiInfo = getConnectionInfo();
		String bssid = null;
		if (mWifiInfo != null && isWifiConnected()) {
			bssid = mWifiInfo.getBSSID();
		}
		return bssid;
	}

	// get the wifi info which is "connected" in wifi-setting
	public WifiInfo getConnectionInfo() {
		WifiManager mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
		return wifiInfo;
	}

	private boolean isWifiConnected() {
		NetworkInfo mWiFiNetworkInfo = getWifiNetworkInfo();
		boolean isWifiConnected = false;
		if (mWiFiNetworkInfo != null) {
			isWifiConnected = mWiFiNetworkInfo.isConnected();
		}
		return isWifiConnected;
	}

	public void startScan() {
		mWifiManager.startScan();
		// 得到扫描结果
		mWifiList = mWifiManager.getScanResults();
		mAPList = new ArrayList<ScanResult>();
		// 得到配置好的网络连接
		mWifiConfiguration = mWifiManager.getConfiguredNetworks();
	}

	// 得到配置好的网络
	public List<WifiConfiguration> getConfiguration() {
		return mWifiConfiguration;
	}

	// 查看扫描结果
	public boolean is5G(String mSsid) {
		boolean ret = false;
		for (int i = 0; i < mWifiList.size(); i++) {
			Log.d("test", "wifi = " + mWifiList.get(i).toString());
			// 将ScanResult信息转换成一个字符串包
			// 其中把包括：BSSID、SSID、capabilities、frequency、level
			String aSSID = mWifiList.get(i).SSID.replace("\"", "");
			mSsid = mSsid.replace("\"", "");
			if (aSSID.equals(mSsid)) {
				if (mWifiList.get(i).frequency >= 5000) {
					ret = true;
				}
			}
		}
		return ret;
	}

	private NetworkInfo getWifiNetworkInfo() {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		return mWiFiNetworkInfo;
	}

	public WifiInfo getWifiInfo() {
		mWifiInfo = mWifiManager.getConnectionInfo();
		return mWifiInfo;
	}

	// 得到网络列表
	public List<ScanResult> getWifiList() {
		return mWifiList;
	}

	// 得到以“DotStone-USB”开头的AP热点
	public List<ScanResult> getAPList() {
		mWifiList = mWifiManager.getScanResults();
		for (int i = 0; i < mWifiList.size(); i++) {
			if (mWifiList.get(i).SSID.startsWith("DotStone-USB")) {
				mAPList.add(mWifiList.get(i));
			}
		}
		return mAPList;
	}

	public WifiConfiguration createWifiConfiguration(String SSID, String Password) {
		int type = getSecurity(SSID, Password);
		Log.i("WifiAdmin", "WifiConfiguration type:" + type);
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
		config.SSID = "\"" + SSID + "\"";
		if (type == SECURITY_NONE) // WIFICIPHER_NOPASS
		{
			config.allowedKeyManagement.set(KeyMgmt.NONE);
		}
		if (type == SECURITY_WEP) // WIFICIPHER_WEP
		{
			config.hiddenSSID = true;
			config.wepKeys[0] = "\"" + Password + "\"";
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
			config.allowedKeyManagement.set(KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		}
		if (type == SECURITY_PSK) // WIFICIPHER_WPA
		{
			config.preSharedKey = "\"" + Password + "\"";
			config.hiddenSSID = true;
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
			config.status = WifiConfiguration.Status.ENABLED;
		}
		return config;
	}

	private int getSecurity(WifiConfiguration config) {
		Log.i("WifiAdmin", "getSecurity ssid:");

		if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
			return SECURITY_PSK;
		}
		if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
			return SECURITY_EAP;
		}
		return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
	}

	private int getSecurity(String ssid, String pwd) {

		if (mWifiList == null)
			if (pwd == null || pwd.equals("")) {
				return SECURITY_NONE;
			} else {
				return SECURITY_PSK;

			}
		int type = SECURITY_PSK;
		boolean isHave = false;
		for (ScanResult scan : mWifiList) {
			if (scan.SSID != null && scan.SSID.equals(ssid)) {
				isHave = true;
				if (scan.capabilities != null)
					if (scan.capabilities.contains("PSK") || scan.capabilities.contains("psk")) {

						return SECURITY_PSK;
					} else if (scan.capabilities.contains("WEP") || scan.capabilities.contains("wep")) {

						return SECURITY_WEP;
					} else {
						return SECURITY_NONE;
					}
			}

		}
		if (!isHave)
			if (pwd == null || pwd.equals("")) {
				return SECURITY_NONE;
			} else {
				return SECURITY_PSK;

			}
		return type;
	}

	// 添加一个网络并连接
	public void addNetwork(WifiConfiguration wcg) {
		int wcgID = mWifiManager.addNetwork(wcg);
		boolean b = mWifiManager.enableNetwork(wcgID, true);
		if (b) {
			mWifiManager.removeNetwork(wcg.networkId);
		}

	}
	
	public WifiConfiguration IsExsits(String SSID) {
		List<WifiConfiguration> existingConfigs = mWifiManager
				.getConfiguredNetworks();
		for (WifiConfiguration existingConfig : existingConfigs) {
			if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
				return existingConfig;
			}
		}
		return null;
	}
	
	public void enableNetwork(int id,boolean b){
		mWifiManager.enableNetwork(id, b);
	}

}
